/*
 * Box.cpp
 *
 *  Created on: Nov 24, 2013
 *      Author: thanhkm
 */

#include <cv.h>
#include <highgui.h>

#include <vector>

void boxMinimala(cv::Mat &frame, cv::Mat &output);

int mainaa(int argc, char* argv[])
{
    cv::Mat img = cv::imread(argv[1]);
    cv::Mat output;

    boxMinimala(img, output);

    cv::imshow("input", img);
    cv::imshow("output", output);
	cvWaitKey(0);

//    // Convert RGB Mat to GRAY
//    cv::Mat gray;
//    cv::cvtColor(img, gray, CV_BGR2GRAY);
//
//    // Store the set of points in the image before assembling the bounding box
//    std::vector<cv::Point> points;
//    cv::Mat_<uchar>::iterator it = gray.begin<uchar>();
//    cv::Mat_<uchar>::iterator end = gray.end<uchar>();
//    for (; it != end; ++it)
//    {
//        if (*it) points.push_back(it.pos());
//    }
//
//    // Compute minimal bounding box
//    cv::RotatedRect box = cv::minAreaRect(cv::Mat(points));
//
//	// Draw bounding box in the original image (debug purposes)
//	cv::Point2f vertices[4];
//	box.points(vertices);
//	for (int i = 0; i < 4; ++i)
//	{
//			cv::line(img, vertices[i], vertices[(i + 1) % 4], cv::Scalar(0, 255, 0), 1, CV_AA);
//	}
//	cv::imshow("box", img);
//	cv::imwrite("box.png", img);

//    // Set Region of Interest to the area defined by the box
//    cv::Rect roi;
//    roi.x = box.center.x - (box.size.width / 2);
//    roi.y = box.center.y - (box.size.height / 2);
//    roi.width = box.size.width;
//    roi.height = box.size.height;
//
//    // Crop the original image to the defined ROI
//    cv::Mat crop = img(roi);
//    cv::imshow("crop", crop);
//
//    cv::imwrite("cropped.png", crop);
//    cvWaitKey(0);

    return 0;
}

void boxMinimala(cv::Mat &img, cv::Mat &output){
	// Convert RGB Mat to GRAY
	cv::Mat gray;
	cv::cvtColor(img, gray, CV_BGR2GRAY);

	// Store the set of points in the image before assembling the bounding box
	std::vector<cv::Point> points;
	cv::Mat_<uchar>::iterator it = gray.begin<uchar>();
	cv::Mat_<uchar>::iterator end = gray.end<uchar>();
	for (; it != end; ++it)
	{
		if (*it) points.push_back(it.pos());
	}

	// Compute minimal bounding box
	cv::RotatedRect box = cv::minAreaRect(cv::Mat(points));

	// Draw bounding box in the original image (debug purposes)
	cv::Point2f vertices[4];
	box.points(vertices);
	img.copyTo(output);

	for (int i = 0; i < 4; ++i)
	{
			cv::line(output, vertices[i], vertices[(i + 1) % 4], cv::Scalar(0, 255, 0), 1, CV_AA);
	}
}
